<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <!-- 警告区 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="catOpt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            style="width: 20%"
            v-model="selectedCateKeys"
            :options="cateList"
            expandTrigger="hover"
            :props="cateProps"
            @change="cateHandleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            size="mini"
            type="primary"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
          >
            添加参数
          </el-button>
          <el-table :data="manyTableData">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 所有从数据库得到的标签信息 -->
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="deleteTagById(index, scope.row)"
                >
                  {{ item }}</el-tag
                >
                <!-- 添加标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  style="width: 120px"
                  size="small"
                  @keyup.enter.native="doNothing(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteById(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            size="mini"
            type="primary"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
          >
            添加属性
          </el-button>
          <el-table :data="onlyTableData">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 所有从数据库得到的标签信息 -->
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="deleteTagById(index, scope.row)"
                >
                  {{ item }}</el-tag
                >
                <!-- 添加标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  style="width: 120px"
                  size="small"
                  @keyup.enter.native="doNothing(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteById(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + this.titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改' + this.titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getCateList();
  },
  data() {
    return {
      // 商品列表
      cateList: [],
      // 级联选择器选中的数据
      selectedCateKeys: [],
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 当前tabs选中的tab
      activeName: "many",
      // 动态参数列表
      manyTableData: [],
      // 静态属性列表
      onlyTableData: [],
      // 用于显示或隐藏添加参数/属性对话框
      addDialogVisible: false,
      // 添加参数表单的数据
      addForm: {
        attr_name: "",
      },
      // 添加参数的表单规则
      addFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
      // 用于显示修改对话框显示或隐藏
      editDialogVisible: false,
      // 修改参数的表单数据
      editForm: {
        attr_name: "",
      },
      // 修改参数的表单规则
      editFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    // 获取所有商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品列表失败！");
      }
      this.cateList = res.data;
    },
    // 当级联选择器选中项改变时调用该函数
    cateHandleChange() {
      this.getParamsData();
    },
    // 当tabs切换tab时响应的函数
    handleTabClick() {
      this.getParamsData();
    },
    // 获取参数列表数据
    async getParamsData() {
      // 如果选中的不是三级分类,清空选中列表
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = [];
        // 下面两句必须加上，要不然会出现bug
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      }

      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName,
          },
        }
      );

      if (res.meta.status !== 200) {
        return this.$message.error("获取参数列表失败！");
      }

      // 将参数的attr_vals属性由字符串变为数组
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        // 控制本条数据的添加标签是按钮模式还是输入框模式
        item.inputVisible = false;
        // 添加本条数据的标签按钮输入框模式时输入的值
        item.inputValue = "";
      });

      console.log(res.data);

      if (this.activeName === "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data;
      }
    },

    // 添加参数对话框关闭时调用的函数
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },

    // 单击确定按钮，发送添加参数请求
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        }
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 201) {
          return this.$message.error("添加参数失败！");
        }
        this.$message.success("添加参数成功！");
        this.addDialogVisible = false;
        this.getParamsData();
      });
    },

    // 显示修改参数的对话框
    async showEditDialog(id) {
      this.editDialogVisible = true;
      // 根据id查询参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${id}`,
        {
          params: {
            attr_sel: this.activeName,
          },
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("得到参数信息失败！");
      }
      this.editForm = res.data;
    },

    // 修改参数对话框关闭时的响应函数
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },

    // 单击确定按钮，发送修改参数的请求
    editParams() {
      // 先进行预验证
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        }
        // 发送修改参数请求
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          }
        );

        if (res.meta.status !== 200) {
          return this.$message.error("修改参数失败！");
        }
        this.$message.success("修改参数成功！");
        this.editDialogVisible = false;
        this.getParamsData();
      });
    },

    // 根据id删除参数
    deleteById(attr_id) {
      this.$confirm("此操作将永久删除该参数, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.cateId}/attributes/${attr_id}`
          );

          if (res.meta.status !== 200) {
            return this.$messgae.error("删除失败！");
          }

          this.$message({
            type: "success",
            message: "删除成功!",
          });

          this.getParamsData();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 当添加标签功能输入确认时响应的函数
    async handleInputConfirm(item) {
      // 当输入内容非法时
      if (item.inputValue.trim().length === 0) {
        item.inputValue = "";
        item.inputVisible = false;
        return;
      }
      // 当输入内容合法时进行的操作
      item.attr_vals.push(item.inputValue.trim());

      this.saveTags(item);
    },

    // 这是回车事件的响应函数，之所以这样做是为了解决回车调用两次对应的BUG
    doNothing(item) {
      // 当输入内容非法时
      if (item.inputValue.trim().length === 0) {
        item.inputValue = "";
        item.inputVisible = false;
        return;
      }
      item.inputVisible = false;
    },

    // 封装出来的保存标签函数
    async saveTags(item) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${item.attr_id}`,
        {
          attr_name: item.attr_name,
          attr_sel: item.attr_sel,
          attr_vals: item.attr_vals.join(" "),
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("修改失败！");
      }
      item.inputVisible = false;
      this.$message.success("修改成功！");
    },

    // 当添加标签功能单击按钮时响应的函数
    showInput(item) {
      item.inputVisible = true;
      // 由按钮模式切换到输入框模式后，立刻获取焦点
      // $nextTick 方法的作用，就是当页面上元素被重新渲染之后，才会指定回调函数中的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 当删除标签功能输入确认时响应的函数
    deleteTagById(index, item) {
      item.attr_vals.splice(index, 1);
      this.saveTags(item);
    },
  },
  computed: {
    // 判断按钮是否被禁用的计算属性
    isBtnDisabled() {
      if (this.selectedCateKeys.length !== 3) {
        return true;
      }
      return false;
    },
    // 当前选中的分类id
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2];
      }
      return null;
    },
    //  对话框标题文本
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      }
      return "静态属性";
    },
  },
};
</script>

<style>
.catOpt {
  margin: 15px 0;
}
</style>